package com.ericcarlisle.howler
{
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;

	[Bindable]
	public class PlayList extends ArrayCollection
	{
		public var _index:uint = 0;
		
		public function set index(value:int):void 
		{ 
			this._index = value; 
			dispatchEvent(new Event(PlayerEvents.INDEX_CHANGE));
		}
		
		// Special binding is required on these custom getters.  All getters will return a different 
		// value if the "index_changed" event is fired.
		[Bindable(index_change)]public function get index():int { return this._index;}
		[Bindable(index_change)]public function get album():String { return this[_index]["album"]; }
		[Bindable(index_change)]public function get artist():String { return this[_index]["artist"]; }
		[Bindable(index_change)]public function get duration():Number { return Number(this[_index]["duration"]); }
		[Bindable(index_change)]public function get genre():String { return this[_index]["genre"]; }
		[Bindable(index_change)]public function get title():String { return this[_index]["title"]; }
		[Bindable(index_change)]public function get track():String { return this[_index]["track"]; }
		[Bindable(index_change)]public function get url():String { return this[_index]["url"]; }
		[Bindable(index_change)]public function get year():String { return this[_index]["year"]; }
		
		// Add a sound file to the playlist.
		public function addSound(title:String, album:String, artist:String, track:String, year:String, genre:String, duration:int, url:String):Boolean
		{
			// Boolean to check for duplicate list item.
			var isDuplicate:Boolean = false;
			var isValid:Boolean = true;
			var soundTitle:String = title;
			
			// Only accept mp3 files (for this version).
			if (Utility.getFileExtension(url) != "mp3")
			{
				isValid = false;
			}
			
			if (isValid)
			{
				// If ID3 tags are emtry, use filename for the title.
				if (soundTitle == null || soundTitle == "")
				{
					soundTitle = Utility.getFileName(url);
				}
				
				// Look through playlist.
				for (var i:int=0; i < this.length; i++)
				{
					
					// If a duplicate url, update the item.
					if (this[i]["url"] == url)
					{
						this.setItemAt({title: soundTitle, album: album, artist: artist, track: track, year: year, genre: genre, duration: duration, url: url}, i);
						isDuplicate = true;
					}
				}
				
				// If not a duplicate, add the item.
				if (!isDuplicate)
				{
					this.addItem({title: soundTitle, album: album, artist: artist, track: track, year: year, genre: genre, duration: duration, url: url});
				}

			}
			return isValid;
		}

		// Remove a sound file to the playlist.
		public function removeSound(index:uint):void
		{
			this.removeItemAt(index);
		}
	}
}